package com.example.backend.rest;

import com.example.backend.mapper.ProductMapper;
import com.example.backend.model.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductRest {

    @Autowired
    SqlSessionFactory factory;

    @GetMapping("all")
    public List<Product> allProduct(){
        SqlSession sess = factory.openSession();
        ProductMapper mapper = sess.getMapper(ProductMapper.class);
        List<Product> prods = mapper.allProducts();
        sess.close();
        return prods;
    }

    @GetMapping("id/{id}")
    public Product productById(@PathVariable("id") int id){
        SqlSession sess = factory.openSession();
        ProductMapper mapper = sess.getMapper(ProductMapper.class);
        Product prod = mapper.selectByPrimaryKey(id);
        sess.close();
        return prod;
    }

    @GetMapping("remove/{id}")
    public int removeProduct(@PathVariable("id") int id){
        SqlSession sess = factory.openSession();
        ProductMapper mapper = sess.getMapper(ProductMapper.class);
        int i = mapper.deleteByPrimaryKey(id);
        sess.close();
        return i;
    }

    //consumes: 表示接收到的数据格式
    @PostMapping(value = "update", consumes = MediaType.APPLICATION_JSON_VALUE)
    public int updateProduct(@RequestBody Product pro){
        SqlSession sess = factory.openSession();
        ProductMapper mapper = sess.getMapper(ProductMapper.class);
        int i = mapper.updateByPrimaryKeySelective(pro);
        sess.close();
        return i;
    }

    @PostMapping(value = "new", consumes = MediaType.APPLICATION_JSON_VALUE)
    public int newProduct(@RequestBody Product pro, BindingResult result){
        System.out.println( pro );
//        if(result.hasErrors()){
//            result.getAllErrors().stream().forEach( error->{
//                FieldError fieldError = (FieldError)error;
//                if(fieldError.getField().equals("id")){
//                    errormsgs.put("id", "用户的ID必须是数字，而不是"+ fieldError.getRejectedValue());
//                    baduser.put("id", fieldError.getRejectedValue().toString());
//                }
//                if(fieldError.getField().equals("dob")){
//                    errormsgs.put("dob", "日期格式是年-月-日");
//                    baduser.put("dob", fieldError.getRejectedValue().toString());
//                }
//
//            } );
//
//        }

        SqlSession sess = factory.openSession();
        ProductMapper mapper = sess.getMapper(ProductMapper.class);
        int i = mapper.insertSelective(pro);
        sess.close();
        System.out.println( i );
        return i;
    }

}
